<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>虚拟银行系统 - 首页</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
  <link rel="stylesheet" href="/css/main.css">
  <style>
    /* Dashboard specific styles */
    .dashboard-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: var(--spacing-lg);
    }
    
    .dashboard-welcome {
      margin-right: var(--spacing-lg);
    }
    
    .dashboard-welcome-title {
      font-size: 24px;
      font-weight: 600;
      margin-bottom: var(--spacing-xs);
    }
    
    .dashboard-welcome-subtitle {
      color: var(--light-text);
    }
    
    .dashboard-date {
      color: var(--light-text);
      padding: var(--spacing-sm) var(--spacing-md);
      background-color: rgba(0, 0, 0, 0.03);
      border-radius: var(--border-radius-md);
      font-size: 13px;
    }
    
    .stats-grid {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: var(--spacing-md);
      margin-bottom: var(--spacing-lg);
    }
    
    .quick-actions {
      display: grid;
      grid-template-columns: repeat(4, 1fr);
      gap: var(--spacing-md);
      margin-bottom: var(--spacing-lg);
    }
    
    .action-card {
      background-color: white;
      border-radius: var(--border-radius-lg);
      padding: var(--spacing-md);
      text-align: center;
      box-shadow: var(--card-shadow);
      transition: transform 0.3s, box-shadow 0.3s;
      cursor: pointer;
    }
    
    .action-card:hover {
      transform: translateY(-5px);
      box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
    }
    
    .action-icon {
      width: 50px;
      height: 50px;
      margin: 0 auto var(--spacing-sm);
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
    }
    
    .action-icon.blue {
      background-color: rgba(26, 58, 143, 0.1);
      color: var(--primary-color);
    }
    
    .action-icon.green {
      background-color: rgba(82, 196, 26, 0.1);
      color: var(--success-color);
    }
    
    .action-icon.orange {
      background-color: rgba(255, 153, 0, 0.1);
      color: var(--accent-color);
    }
    
    .action-icon.purple {
      background-color: rgba(125, 83, 231, 0.1);
      color: #7d53e7;
    }
    
    .action-title {
      font-weight: 500;
      margin-bottom: var(--spacing-xs);
    }
    
    .action-description {
      font-size: 12px;
      color: var(--light-text);
    }
    
    .sections-grid {
      display: grid;
      grid-template-columns: 2fr 1fr;
      gap: var(--spacing-lg);
    }
    
    .transaction-item {
      display: flex;
      align-items: center;
      padding: var(--spacing-md) 0;
      border-bottom: 1px solid var(--divider-color);
    }
    
    .transaction-item:last-child {
      border-bottom: none;
    }
    
    .transaction-icon {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: var(--spacing-md);
      flex-shrink: 0;
    }
    
    .transaction-icon.income {
      background-color: rgba(82, 196, 26, 0.1);
      color: var(--success-color);
    }
    
    .transaction-icon.expense {
      background-color: rgba(245, 34, 45, 0.1);
      color: var(--error-color);
    }
    
    .transaction-info {
      flex: 1;
      min-width: 0;
    }
    
    .transaction-title {
      font-weight: 500;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .transaction-subtitle {
      font-size: 12px;
      color: var(--light-text);
    }
    
    .transaction-amount {
      font-weight: 600;
      text-align: right;
    }
    
    .transaction-amount.income {
      color: var(--success-color);
    }
    
    .transaction-amount.expense {
      color: var(--error-color);
    }
    
    .product-item {
      display: flex;
      padding: var(--spacing-md) 0;
      border-bottom: 1px solid var(--divider-color);
    }
    
    .product-item:last-child {
      border-bottom: none;
    }
    
    .product-info {
      flex: 1;
      min-width: 0;
    }
    
    .product-title {
      font-weight: 500;
      margin-bottom: 4px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    
    .product-subtitle {
      font-size: 12px;
      color: var(--light-text);
      margin-bottom: 4px;
    }
    
    .product-return {
      font-weight: 600;
      color: var(--accent-color);
    }
    
    /* Responsive */
    @media (max-width: 991px) {
      .stats-grid {
        grid-template-columns: repeat(2, 1fr);
      }
      
      .quick-actions {
        grid-template-columns: repeat(2, 1fr);
      }
      
      .sections-grid {
        grid-template-columns: 1fr;
      }
    }
    
    @media (max-width: 575px) {
      .dashboard-header {
        flex-direction: column;
        align-items: flex-start;
      }
      
      .dashboard-date {
        margin-top: var(--spacing-sm);
      }
      
      .stats-grid {
        grid-template-columns: 1fr;
      }
    }
  </style>
</head>
<body>
  <div class="app-wrapper">
    <!-- Top Navigation Bar -->
    <div id="top-navbar"></div>
    
    <div class="main-container">
      <!-- Sidebar -->
      <div id="sidebar"></div>
      
      <!-- Main Content -->
      <div class="content">
        <div class="dashboard-header">
          <div class="dashboard-welcome">
            <h1 class="dashboard-welcome-title">欢迎回来，<span id="user-display-name">用户</span></h1>
            <p class="dashboard-welcome-subtitle">这里是您的账户概览</p>
          </div>
          <div class="dashboard-date" id="current-date">2023年1月1日 星期一</div>
        </div>
        
        <!-- Stats Cards -->
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-card-icon">
              <i class="fas fa-wallet"></i>
            </div>
            <div class="stat-card-content">
              <div class="stat-card-title">账户余额</div>
              <div class="stat-card-value" id="account-balance">¥0.00</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-card-icon">
              <i class="fas fa-exchange-alt"></i>
            </div>
            <div class="stat-card-content">
              <div class="stat-card-title">本月交易</div>
              <div class="stat-card-value" id="monthly-transactions">0 笔</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-card-icon">
              <i class="fas fa-chart-line"></i>
            </div>
            <div class="stat-card-content">
              <div class="stat-card-title">理财总额</div>
              <div class="stat-card-value" id="investment-total">¥0.00</div>
            </div>
          </div>
        </div>
        
        <!-- Quick Actions -->
        <h2 class="section-title mb-3">快捷操作</h2>
        <div class="quick-actions">
          <div class="action-card" id="action-transfer">
            <div class="action-icon blue">
              <i class="fas fa-exchange-alt"></i>
            </div>
            <div class="action-title">转账</div>
            <div class="action-description">向他人转账</div>
          </div>
          
          <div class="action-card" id="action-recharge">
            <div class="action-icon green">
              <i class="fas fa-plus-circle"></i>
            </div>
            <div class="action-title">充值</div>
            <div class="action-description">向账户充值</div>
          </div>
          
          <div class="action-card" id="action-withdraw">
            <div class="action-icon orange">
              <i class="fas fa-minus-circle"></i>
            </div>
            <div class="action-title">提现</div>
            <div class="action-description">提取资金到银行卡</div>
          </div>
          
          <div class="action-card" id="action-invest">
            <div class="action-icon purple">
              <i class="fas fa-shopping-cart"></i>
            </div>
            <div class="action-title">购买理财</div>
            <div class="action-description">选购理财产品</div>
          </div>
        </div>
        
        <!-- Transaction History & Product Recommendations -->
        <div class="sections-grid">
          <!-- Recent Transactions -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">近期交易</h3>
              <a href="/transactions.html" class="btn-link">查看全部</a>
            </div>
            <div class="card-body">
              <div id="recent-transactions-list">
                <div class="loader-container">
                  <div class="loader"></div>
                </div>
              </div>
            </div>
          </div>
          
          <!-- Product Recommendations -->
          <div class="card">
            <div class="card-header">
              <h3 class="card-title">理财推荐</h3>
              <a href="/financial.html" class="btn-link">查看全部</a>
            </div>
            <div class="card-body">
              <div id="product-recommendations-list">
                <div class="loader-container">
                  <div class="loader"></div>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- Announcements -->
        <div class="card mt-4">
          <div class="card-header">
            <h3 class="card-title">系统公告</h3>
          </div>
          <div class="card-body">
            <div id="announcements-list">
              <div class="alert alert-info">
                <div class="alert-icon">
                  <i class="fas fa-info-circle"></i>
                </div>
                <div>
                  <strong>系统升级通知：</strong>
                  为提升用户体验，系统将于近期进行升级维护，具体时间另行通知。
                </div>
              </div>
              <div class="alert alert-warning">
                <div class="alert-icon">
                  <i class="fas fa-exclamation-triangle"></i>
                </div>
                <div>
                  <strong>账户安全提示：</strong>
                  请勿将账号密码告知他人，谨防诈骗信息。
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script src="/js/utils/Utils.js"></script>
  <script src="/js/components/Toast.js"></script>
  <script src="/js/services/ApiService.js"></script>
  <script src="/js/components/TopNavBar.js"></script>
  <script src="/js/components/SideBar.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      // Check if user is authenticated
      if (ApiService.redirectIfNotAuthenticated()) {
        return;
      }
      
      // Initialize components
      const topNavBar = new TopNavBar();
      topNavBar.init();
      
      const sideBar = new SideBar();
      sideBar.init('dashboard');
      
      // Update current date
      updateCurrentDate();
      
      // Load user data
      loadUserData();
      
      // Load account balance
      loadAccountBalance();
      
      // Load monthly transactions
      loadMonthlyTransactions();
      
      // Load investment total
      loadInvestmentTotal();
      
      // Load recent transactions
      loadRecentTransactions();
      
      // Load product recommendations
      loadProductRecommendations();
      
      // Bind quick action buttons
      bindQuickActions();
    });
    
    /**
     * Update current date display
     */
    function updateCurrentDate() {
      const dateElement = document.getElementById('current-date');
      const now = new Date();
      
      const options = {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        weekday: 'long'
      };
      
      dateElement.textContent = now.toLocaleDateString('zh-CN', options);
    }
    
    /**
     * Load user data
     */
    function loadUserData() {
      const userDisplayNameElement = document.getElementById('user-display-name');
      
      // Try to get user info from localStorage first (for quick display)
      const userInfo = localStorage.getItem('userInfo');
      if (userInfo) {
        const user = JSON.parse(userInfo);
        userDisplayNameElement.textContent = user.username || '用户';
      }
      
      // Then fetch fresh data from API
      ApiService.get('/api/user/info')
        .then(response => {
          if (response.code === 0 && response.data) {
            const user = response.data;
            userDisplayNameElement.textContent = user.username || '用户';
            
            // Update stored user info
            localStorage.setItem('userInfo', JSON.stringify(user));
          }
        })
        .catch(error => {
          console.error('Error loading user info:', error);
        });
    }
    
    /**
     * Load account balance
     */
    function loadAccountBalance() {
      const balanceElement = document.getElementById('account-balance');
      
      ApiService.get('/api/account/balance')
        .then(response => {
          if (response.code === 0 && response.data) {
            const balanceData = response.data;
            balanceElement.textContent = Utils.formatMoney(balanceData.availableBalance);
          }
        })
        .catch(error => {
          console.error('Error loading balance:', error);
          balanceElement.textContent = '加载失败';
        });
    }
    
    /**
     * Load monthly transactions count
     */
    function loadMonthlyTransactions() {
      const transactionsElement = document.getElementById('monthly-transactions');
      
      // Get first and last day of current month
      const now = new Date();
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1);
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0);
      
      const startDate = firstDay.toISOString();
      const endDate = lastDay.toISOString();
      
      ApiService.get('/api/transaction/list', { startDate, endDate, page: 1, size: 1 })
        .then(response => {
          if (response.code === 0 && response.data) {
            const total = response.data.total || 0;
            transactionsElement.textContent = `${total} 笔`;
          }
        })
        .catch(error => {
          console.error('Error loading transactions count:', error);
          transactionsElement.textContent = '加载失败';
        });
    }
    
    /**
     * Load investment total
     */
    function loadInvestmentTotal() {
      const investmentElement = document.getElementById('investment-total');
      
      ApiService.get('/api/finance/summary')
        .then(response => {
          if (response.code === 0 && response.data) {
            const summary = response.data;
            investmentElement.textContent = Utils.formatMoney(summary.totalInvestment || 0);
          }
        })
        .catch(error => {
          console.error('Error loading investment summary:', error);
          investmentElement.textContent = '加载失败';
        });
    }
    
    /**
     * Load recent transactions
     */
    function loadRecentTransactions() {
      const transactionsListElement = document.getElementById('recent-transactions-list');
      
      ApiService.get('/api/transaction/list', { page: 1, size: 5 })
        .then(response => {
          if (response.code === 0 && response.data) {
            const transactions = response.data.list || [];
            
            if (transactions.length === 0) {
              transactionsListElement.innerHTML = `
                <div class="empty-state">
                  <p>暂无交易记录</p>
                </div>
              `;
              return;
            }
            
            let html = '';
            transactions.forEach(transaction => {
              const isIncome = [1, 5].includes(transaction.tradeType); // 充值或退款
              const iconClass = isIncome ? 'income' : 'expense';
              const amountPrefix = isIncome ? '+' : '-';
              
              html += `
                <div class="transaction-item" data-id="${transaction.id}">
                  <div class="transaction-icon ${iconClass}">
                    <i class="fas ${isIncome ? 'fa-arrow-down' : 'fa-arrow-up'}"></i>
                  </div>
                  <div class="transaction-info">
                    <div class="transaction-title">${transaction.tradeTypeName}</div>
                    <div class="transaction-subtitle">${Utils.formatDate(transaction.createTime, true)}</div>
                  </div>
                  <div class="transaction-amount ${iconClass}">
                    ${amountPrefix}¥${Math.abs(transaction.amount).toFixed(2)}
                  </div>
                </div>
              `;
            });
            
            transactionsListElement.innerHTML = html;
            
            // Add click event to view transaction details
            const transactionItems = document.querySelectorAll('.transaction-item');
            transactionItems.forEach(item => {
              item.addEventListener('click', () => {
                const id = item.getAttribute('data-id');
                window.location.href = `/transaction-detail.html?id=${id}`;
              });
            });
          }
        })
        .catch(error => {
          console.error('Error loading transactions:', error);
          transactionsListElement.innerHTML = `
            <div class="empty-state">
              <p>加载失败，请稍后再试</p>
            </div>
          `;
        });
    }
    
    /**
     * Load product recommendations
     */
    function loadProductRecommendations() {
      const recommendationsListElement = document.getElementById('product-recommendations-list');
      
      ApiService.get('/api/finance/product/hot', { limit: 3 })
        .then(response => {
          if (response.code === 0 && response.data) {
            const products = response.data.list || [];
            
            if (products.length === 0) {
              recommendationsListElement.innerHTML = `
                <div class="empty-state">
                  <p>暂无推荐产品</p>
                </div>
              `;
              return;
            }
            
            let html = '';
            products.forEach(product => {
              html += `
                <div class="product-item" data-id="${product.id}">
                  <div class="product-info">
                    <div class="product-title">${product.productName}</div>
                    <div class="product-subtitle">期限 ${product.duration} 天 | 起投 ¥${product.minAmount}</div>
                    <div class="product-return">${product.expectedReturn}%</div>
                  </div>
                  <button class="btn btn-sm btn-outline">购买</button>
                </div>
              `;
            });
            
            recommendationsListElement.innerHTML = html;
            
            // Add click event to view product details
            const productItems = document.querySelectorAll('.product-item');
            productItems.forEach(item => {
              item.addEventListener('click', (e) => {
                // Don't trigger if clicking the button
                if (e.target.tagName === 'BUTTON') {
                  return;
                }
                
                const id = item.getAttribute('data-id');
                window.location.href = `/product-detail.html?id=${id}`;
              });
              
              // Buy button
              const buyButton = item.querySelector('button');
              if (buyButton) {
                buyButton.addEventListener('click', () => {
                  const id = item.getAttribute('data-id');
                  window.location.href = `/product-purchase.html?id=${id}`;
                });
              }
            });
          }
        })
        .catch(error => {
          console.error('Error loading product recommendations:', error);
          recommendationsListElement.innerHTML = `
            <div class="empty-state">
              <p>加载失败，请稍后再试</p>
            </div>
          `;
        });
    }
    
    /**
     * Bind quick action buttons
     */
    function bindQuickActions() {
      // Transfer
      document.getElementById('action-transfer').addEventListener('click', () => {
        window.location.href = '/transfer.html';
      });
      
      // Recharge
      document.getElementById('action-recharge').addEventListener('click', () => {
        window.location.href = '/recharge.html';
      });
      
      // Withdraw
      document.getElementById('action-withdraw').addEventListener('click', () => {
        window.location.href = '/withdraw.html';
      });
      
      // Invest
      document.getElementById('action-invest').addEventListener('click', () => {
        window.location.href = '/financial.html';
      });
    }
  </script>
</body>
</html>
